package com.briup.estore.web.filter;

import com.briup.estore.bean.Customer;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 验证登录信息
 */
@WebFilter("/addBookToShopCart")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 变成两个熟悉的对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 分析session里有没有
        HttpSession session = req.getSession();
        Customer user = (Customer)session.getAttribute("user");
        // 如果存在，直接放行
        if(user != null){
            chain.doFilter(req,resp);
            return;
        }
        // 分析cookie里有没有（登录成功之后记得也往cookie里放一份）
        Cookie[] cookies = req.getCookies();
        for(Cookie c : cookies){
            if("userId".equals(c.getName())){
                req.setAttribute("userId",c.getValue());
                chain.doFilter(req,resp);
                return;
            }
        }
        session.setAttribute("msg","请您登录后再操作");
        // 跳转页面
        resp.sendRedirect("login");

    }

    @Override
    public void destroy() {

    }
}
